import os.path
import sqlite3
import time

from waitress import serve
from flask import Flask
from flask import render_template
from flask import request

from result import Result, obj2json
from ftpconnect import myftp  # 单例模式

app = Flask(__name__)  # type:Flask


@app.route('/login/')
@app.route('/')
def login():
    return render_template('login.html')


@app.route('/user/login/', methods=["GET", "POST"])
def user_login():
    username = request.form.get('username')
    password = request.form.get('password')
    if username:
        conn = sqlite3.connect('ignore.db')
        cursor = conn.cursor()
        cursor.execute('create table if not exists user(username varchar(255), password varchar(255))')
        cursor.execute('select * from user')
        values = cursor.fetchall()
        cursor.close()
        conn.close()
        ftp_files_size = {}
        ftp_files_status = {}
        for value in values:
            if value[0] == username:
                if value[1] == password:
                    myftp.login(username, password)
                    myftp.start()
                    if myftp.ftp.pwd() != '/':
                        time.sleep(0.3)
                    for f in myftp.ftpDirs:
                        ftp_files_size[f] = int(myftp.get_size(f)/1024)
                        local_path = myftp.get_local_path(f)
                        ftp_files_status[f] = myftp.get_status(local_path, f)
                    return render_template('home.html', username=username, ftp_files=myftp.ftpDirs,
                                           ftp_files_size=ftp_files_size,
                                           ftp_files_status=ftp_files_status,
                                           current_files=myftp.current_files)
                else:
                    return '密码错误,<a href="/login/">重新登录</a>'
        try:
            myftp.login(username, password)
            myftp.start()
            conn = sqlite3.connect('ignore.db')
            cursor = conn.cursor()
            cursor.execute('insert into user(username, password) values(?,?)', [username, password])
            cursor.close()
            conn.commit()
            conn.close()
            print(f'新加入用户:{username}')
            if myftp.ftp.pwd() != '/':
                time.sleep(0.3)
            for f in myftp.ftpDirs:
                ftp_files_size[f] = myftp.get_size(f)
                local_path = myftp.get_local_path(f)
                ftp_files_status[f] = myftp.get_status(local_path, f)
            return render_template('home.html', username=username, ftp_files=myftp.ftpDirs,
                                   ftp_files_size=ftp_files_size, ftp_files_status=ftp_files_status,
                                   current_files=myftp.current_files)
        except Exception:
            return '该用户不存在,<a href="/login/">重新登录</a>'
    else:
        return '请先<a href="/login/">登录</a>'


# 获取目录大小
@app.route('/get/size/', methods=["GET", "POST"])
def get_size():
    file = request.values.get('file')
    return obj2json(Result('1', '获取成功', myftp.get_size(file)))


# 获取目录同步状态
@app.route('/get/status/', methods=["GET", "POST"])
def get_status():
    file = request.values.get('file')
    local_path = myftp.get_local_path(file)
    return obj2json(Result('1', '获取成功', myftp.get_status(local_path, file)))


# 目录开始同步
@app.route('/current/add/', methods=["GET", "POST"])
def add_current_file():
    file = request.values.get('file')
    flag = myftp.add_current(file)
    if flag is True:
        return obj2json(Result('1', '添加成功'))
    else:
        return obj2json(Result('0', '添加失败'))


# 目录停止同步
@app.route('/current/remove/', methods=["GET", "POST"])
def remove_current_file():
    file = request.values.get('file')
    flag = myftp.remove_current(file)
    if flag is True:
        return obj2json(Result('1', '移除成功'))
    else:
        return obj2json(Result('0', '移除失败'))


# 获取日志
@app.route('/logs/get/', methods=["GET", "POST"])
def get_logs():
    logs = myftp.get_log()
    return obj2json(Result('1', '获取日志成功', str(logs)))


# 刷新
@app.route('/refresh/', methods=["GET", "POST"])
def refresh():
    # myftp.initial()
    myftp.start()
    return obj2json(Result('1', '刷新成功'))


# 获取同步模式
@app.route('/mode/get/', methods=["GET", "POST"])
def get_mode():
    mode = myftp.mode
    return obj2json(Result('1', '获取同步模式成功', mode))


# 设置同步模式
@app.route('/config/mode/', methods=["GET", "POST"])
def set_mode():
    mode = request.values.get('mode')
    myftp.set_mode(int(mode))
    return obj2json(Result('1', '设置同步模式成功'))


# 获取扫描时间
@app.route('/interval/get/', methods=["GET", "POST"])
def get_interval():
    interval = myftp.interval
    return obj2json(Result('1', '获取扫描时间成功', interval))


# 设置扫描时间
@app.route('/config/interval/', methods=["GET", "POST"])
def set_interval():
    interval = request.values.get('interval')
    myftp.set_interval(int(interval))
    return obj2json(Result('1', '设置扫描时间成功'))


# 创建本地目录（并添加映射）
@app.route('/add/local/dir/', methods=["GET", "POST"])
def add_local_dir():
    local_file = request.values.get('local_file')
    ftp_file = request.values.get('ftp_file')
    if not os.path.exists(local_file):
        myftp.add_local_dir(local_file)
    myftp.update_dirs(local_file, ftp_file)
    return obj2json(Result('1', '创建成功'))


# 增加ftp目录并指定与本地目录的映射
@app.route('/ftp/add/', methods=["GET", "POST"])
def add_ftp():
    ftp_dir = request.values.get('ftp_dir')
    local_dir = request.values.get('local_dir')
    flag = myftp.add_ftp(ftp_dir)
    if flag:
        myftp.update_dirs(local_dir, ftp_dir)


# 修改ftp目录与本地目录的映射
@app.route('/update/dirs/', methods=["GET", "POST"])
def update_dirs():
    local_dir = request.values.get('local_dir')
    ftp_dir = request.values.get('ftp_dir')
    myftp.update_dirs(local_dir, ftp_dir)


# 删除ftp目录与本地目录的映射
@app.route('/delete/dirs/', methods=["GET", "POST"])
def del_dirs():
    file = request.values.get('file')
    myftp.del_Dirs(file)


# 开启ftp
@app.route('/start/', methods=["GET", "POST"])
def start():
    myftp.start()


# 停止或继续ftp
@app.route('/stop/', methods=["GET", "POST"])
def stop():
    myftp.stop()


# 获取忽略文件列表
@app.route('/ignore/get/', methods=["GET", "POST"])
def get_ignore():
    ignore_list = myftp.ignore
    return obj2json(Result('1', '获取忽略列表成功', str(ignore_list)))


# 增加忽略文件或目录
@app.route('/ignore/add/', methods=["GET", "POST"])
def add_ignore():
    file = request.values.get('file')
    myftp.add_ignore(file)
    return obj2json(Result('1', '增加忽略成功'))


# 删除忽略文件或目录
@app.route('/ignore/remove/', methods=["GET", "POST"])
def del_ignore():
    file = request.values.get('file')
    myftp.del_ignore(file)
    return obj2json(Result('1', '删除忽略成功'))


# 获取传入目录下的文件
@app.route('/files/get/', methods=["GET", "POST"])
def get_files():
    file = request.values.get('file')
    data = myftp.get_ftp_files(file)
    if data is False:
        return obj2json(Result('0', '这是一个文件'))
    else:
        return obj2json(Result('1', '获取目录下文件成功', str(data)))


# 删除ftp目录
@app.route('/dir/delete/', methods=["GET", "POST"])
def delete_dir():
    file = request.values.get('file')
    flag = myftp.del_ftp(file)
    if flag is True:
        return obj2json(Result('1', '删除ftp目录成功'))
    else:
        return obj2json(Result('0', '删除ftp目录失败'))


# 增加ftp目录
@app.route('/dir/add/', methods=["GET", "POST"])
def add_dir():
    file = request.values.get('file')
    flag = myftp.add_ftp(file)
    if flag is True:
        return obj2json(Result('1', '增加ftp目录成功'))
    else:
        return obj2json(Result('0', '增加ftp目录失败'))


if __name__ == '__main__':
    # myftp = FtpConnect('162.14.109.33', 21, 'anbulang', '@a2624250238')
    # # myftp = FtpConnect('localhost', 21, 'anbulang', '2624250238')
    # myftp.set_interval(10)
    # myftp.set_mode(1)
    # print(myftp.ignore)
    # # print(myftp.Dirs)
    # myftp.start()

    serve(app, host="0.0.0.0", port=5000)
